package common

import (
	"encoding/json"
	"fmt"
	"strings"

	"github.com/garyburd/redigo/redis"
)

type User struct {
	UserId   int
	NickName string
	PassWord string
}

func FindUser(userId int) (user *User, err error) {
	rd := RedisPool.pool.Get()
	userInfo, _ := redis.String(rd.Do("hget", "user", userId))
	fmt.Printf("从redis获取用户信息:%v\n", userInfo)
	userInfo = strings.Trim(userInfo, " \r\n")
	if userInfo == "" {
		return nil, nil
	}
	user = &User{}
	err = json.Unmarshal([]byte(userInfo), &user)
	if err != nil {
		return nil, fmt.Errorf("反序列化用户信息失败")
	}
	return
}

func CreateUser(userId int, passWord string, nickName string) (user *User, err error) {
	user = &User{
		UserId:   userId,
		PassWord: passWord,
		NickName: nickName,
	}
	data, err := json.Marshal(user)
	if err != nil {
		return nil, err
	}
	r := RedisPool.pool.Get()
	_, err = r.Do("hset", "user", userId, string(data))
	if err != nil {
		return nil, err
	}
	return
}
